<template>
  <view>
    <Login ref="loginRef" @login-success="loginSuccess"></Login>
    <MyShare ref="shareRef" :share-params="shareParams" :template-id="routerParams.id" />
    <view class="page template-detail">
      <!-- <image style="width: 100%" mode="widthFix" src="../../assets/templatea.png"></image> -->
      <view class="artistic-text">{{ templateDetail.title1 }}</view>
      <view class="introduce">
        <view class="title-box">
          <view class="title">课程介绍</view>
        </view>
        <view class="content default-box">
          <view class="head">
            <view>适龄</view>
            <view>课程</view>
            <view>课程时长</view>
          </view>
          <view class="value" v-for="item of templateDetail.classMarkList" :key="item.age">
            <view class="age">{{ item.age }}</view>
            <view class="age">{{ item.course }}</view>
            <view class="age">{{ item.time }}</view>
          </view>
        </view>
        <view class="count-down-box">
          <view class="title">活动倒计时</view>
          <view class="count-down">
            <uni-countdown
              color="#EE6B54"
              :font-size="28"
              background-color="#ffffff"
              border-color="#ffffff"
              splitor-color="#ffffff"
              :day="countDown.day"
              :hour="countDown.hour"
              :minute="countDown.minute"
              :second="countDown.second"
            ></uni-countdown>
          </view>
        </view>

        <view class="title-box">
          <view class="title">拼团详情</view>
        </view>

        <view class="role-box default-box">
          <view class="role" v-for="(item, index) of templateDetail.buyMarkList" :key="index">
            {{ item.buyMark }}
          </view>
        </view>

        <view class="title-box">
          <view class="title">拼团规则</view>
        </view>

        <view class="role-box default-box">
          <view class="role" v-for="(item, index) of templateDetail.classRuleList" :key="index">
            {{ item.ruleMark }}
          </view>
        </view>

        <view class="title-box">
          <view class="title">联系校区</view>
        </view>

        <view class="contact-campus-box default-box">
          <view class="contact-campus" v-for="addr of templateDetail.addressList" :key="addr.id">
            <view class="title">
              <view v-for="item of '校区地址'" :key="item">
                {{ item }}
              </view>
            </view>
            <view class="value">{{ addr.address }}</view>
          </view>
        </view>
      </view>

      <!-- 当前用户有无创建过模板 -->
      <view class="bottom-btn" v-if="displayTemplateBtn">
        <view class="right" @tap="proxy.$refs.loginRef.checkLogin()">{{ submitText }}</view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import Login from "@/components/Login/index.vue";
import MyShare from "@/components/MyShare/index.vue";
import dayjs from "dayjs";
const { proxy } = getCurrentInstance();
const userInfoStore = useUserInfoStore();
let submitText = ref("");

let shareParams = reactive({
  visible: true,
  title: "",
  path: ""
  // summary: "五一组团放假描述",
  // content: "五一组团放假内容"
});

let templateDetail = reactive<any>({});

// 是否显示模板下方按钮
let displayTemplateBtn = ref(true);

//倒计时
let countDown = reactive({
  dateTime: "2022-01-01 00:00:00",
  day: 1000,
  hour: 10,
  minute: 10,
  second: 10
});

let routerParams = reactive({
  id: "",
  // created: 创建模板 apply-立即报名
  _type: "",
  activityId: ""
});

onLoad(op => init(op));

/**
 * 初始化
 */
const init = op => {
  Object.assign(routerParams, op);
  console.log(op, "op");

  const { _type } = op;
  if (_type === "created") {
    submitText.value = "创建模板";
  } else if (_type === "apply") {
    submitText.value = "立即报名";
  }

  modelFindModelById({ modelId: routerParams.id }).then(data => {
    Object.assign(templateDetail, data);
    templateDetail.classMarkList = data.classMarkList.map(item => {
      const v = item.classMark.split("/");
      console.log(v, "v");
      return {
        ...item,
        age: v[1],
        course: v[0],
        time: v[2]
      };
    });
    Object.assign(shareParams, {
      title: templateDetail.modelName,
      path: `/pages/templateDetail/index?id=${routerParams.id}&_type=${routerParams._type}&wxCode=${userInfoStore.openId}`
    });

    // 定义目标时间
    const targetTime = dayjs(data.endTime);
    // 获取当前时间
    const now = dayjs();
    // 计算时间差（以毫秒为单位）
    const diffInMs = targetTime.diff(now);

    Object.assign(countDown, {
      day: Math.floor(diffInMs / (1000 * 60 * 60 * 24)),
      hour: Math.floor((diffInMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minute: Math.floor((diffInMs % (1000 * 60 * 60)) / (1000 * 60)),
      second: Math.floor((diffInMs % (1000 * 60)) / 1000)
    });
  });

  if (userInfoStore.openId) {
    const params = {
      wxCode: userInfoStore.openId,
      modelId: op.id,
      pageNum: 1,
      pageSize: 1
    };
    activityFindActivityPage(params).then(data => {
      console.log(data, "data");

      // 如果类型是创建模板，那么如果有创建过那么不在显示可以创建
      if (_type === "created") {
        displayTemplateBtn.value = data.records.length === 0;
      }
    });
    // 添加个人模板浏览量 | 同时会添加模板浏览量
    if (routerParams.activityId) {
      activityUpBrowseCount({
        id: routerParams.activityId
      });
    }
  }
};

const loginSuccess = () => {
  console.log("登录成功", userInfoStore);

  if (userInfoStore.openId) {
    console.log("openId存在");

    // 创建模板，把数据创建后存储到数据库中并返回个人模板列表中
    if (routerParams._type === "created") {
      const createdParams = {
        modelId: routerParams.id,
        wxCode: userInfoStore.openId,
        pageUrl: `/pages/templateDetail/index?id=${routerParams.id}&_type=apply&wxCode=${userInfoStore.openId}`
      };
      console.log("创建?????2222");

      activitySaveActivity(createdParams).then(() => {
        console.log("创建?????33333");

        const params = {
          _type: "apply",
          id: routerParams.id,
          toPath: `/pages/templateDetail/index`
        };
        console.log("模板创建", params);

        uni.setStorageSync(CONSTANT_PARAMS.MY_HOME_PARAMS, params);
        uni.switchTab({
          url: "/pages/my/home/index"
        });
      });
    } else {
      uni.showToast({
        title: "用户点击报名",
        icon: "none"
      });
    }
  } else {
    uni.showToast({ title: "用户未登录", icon: "none" });
  }
};
</script>
<style src="./index.scss" scoped></style>

<style lang="scss">
.template-detail {
  .uni-countdown__number {
    span {
      font-size: 0.65em !important;
    }
  }

  //#ifdef MP-WEIXIN
  .uni-countdown {
    text {
      font-size: 0.9em !important;
    }
  }
  // #endif
}
</style>
